package com.bloveoacom.weight;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.blankj.utilcode.util.ConvertUtils;
import com.bloveoacom.weichi.R;


/**
 * author: zhu.px
 * e-mail: 1271901673@qq.com
 * time  : 2018/5/21
 * desc  : 删除按钮的et
 */
public class DelEditText extends AppCompatEditText {

    /**
     * 删除图标
     */
    private Drawable icDelete;

    /**
     * 删除图标起点(x,y)、删除图标宽、高（px）
     */
    private int delete_x, delete_y, delete_width, delete_height;

    public DelEditText(Context context) {
        this(context, null);
        setSingleLine();
    }

    public DelEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DelEditText);
        final int N = typedArray.getIndexCount();
        for (int i = 0; i < N; i++) {
            initAttr(typedArray.getIndex(i), typedArray);
        }
        if (icDelete != null) {
            if (delete_width == 0 || delete_height == 0) {
                icDelete.setBounds(delete_x, delete_y, icDelete.getMinimumWidth(), icDelete.getMinimumHeight());
            } else {
                icDelete.setBounds(delete_x, delete_y, delete_width, delete_height);
            }
            setCompoundDrawablePadding(ConvertUtils.dp2px(10));
        }
        typedArray.recycle();
    }

    private void initAttr(int index, TypedArray typedArray) {
        if (index == R.styleable.DelEditText_ic_delete) {
            icDelete = typedArray.getDrawable(index);
        } else if (index == R.styleable.DelEditText_delete_width) {
            delete_width = typedArray.getInteger(index, 0);
        } else if (index == R.styleable.DelEditText_delete_height) {
            delete_height = typedArray.getInteger(index, 0);
        } else if (index == R.styleable.DelEditText_delete_x) {
            delete_x = typedArray.getInteger(index, 0);
        } else if (index == R.styleable.DelEditText_delete_y) {
            delete_y = typedArray.getInteger(index, 0);
        }
    }


    /**
     * 复写EditText本身的方法：onTextChanged（）
     * 调用时刻：当输入框内容变化时
     */
    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        // hasFocus()返回是否获得EditTEXT的焦点，即是否选中
        // setDeleteIconVisible（） = 根据传入的是否选中 & 是否有输入来判断是否显示删除图标
        setDeleteIconVisible(hasFocus() && text.length() > 0);
    }

    /**
     * 复写EditText本身的方法：onFocusChanged（）
     * 调用时刻：焦点发生变化时
     */
    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        // focused = 是否获得焦点
        // 同样根据setDeleteIconVisible（）判断是否要显示删除图标->>关注1
        setDeleteIconVisible(focused && length() > 0);
    }

    /**
     * 作用：对删除图标区域设置为"点击 即 清空搜索框内容"
     * 原理：当手指抬起的位置在删除图标的区域，即视为点击了删除图标 = 清空搜索框内容
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 原理：当手指抬起的位置在删除图标的区域，即视为点击了删除图标 = 清空搜索框内容
        switch (event.getAction()) {
            // 判断动作 = 手指抬起时
            case MotionEvent.ACTION_UP:
                Drawable drawable = icDelete;
                if (drawable != null && event.getX() <= (getWidth() - getPaddingRight())
                        && event.getX() >= (getWidth() - getPaddingRight() - drawable.getBounds().width())) {
                    // 判断条件说明
                    // event.getX() ：抬起时的位置坐标
                    // getWidth()：控件的宽度
                    // getPaddingRight():删除图标右边缘至EditText控件右边缘的距离
                    // 即：getWidth() - getPaddingRight() = 删除图标的右边缘坐标 = X1
                    // getWidth() - getPaddingRight() - drawable.getBounds().width() = 删除图标左边缘的坐标 = X2
                    // 所以X1与X2之间的区域 = 删除图标的区域
                    // 当手指抬起的位置在删除图标的区域（X2=<event.getX() <=X1），即视为点击了删除图标 = 清空搜索框内容
                    setText("");
                }
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 判断是否显示删除图标
     */
    private void setDeleteIconVisible(boolean deleteVisible) {
        setCompoundDrawables(null, null, deleteVisible ? icDelete : null, null);
    }
}
